<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | 王勇程 <laughskydragon@qq.com>                         |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\api\logic;

use app\common\logic\Announcement as CommonAnnouncement;

/**
 * 公告接口逻辑
 */
class Announcement extends ApiBase
{
    
    public static $commonAnnouncementLogic = null;
    
    /**
     * 基类初始化
     */
    public function __construct()
    {
        // 执行父类构造方法
        parent::__construct();
        
        empty(static::$commonAnnouncementLogic) && static::$commonAnnouncementLogic = new CommonAnnouncement();
    }
    
    /**
     * 获取公告列表
     * @author 王勇程 <laughskydragon@qq.com>
     * @param array $data
     * @return array
     */
    public function getAnnouncementList($data = [])
    {
        // 1. JWT解析获取user_id
        $token = $data['user_token'] ?? '';
        if (!empty($token)) {
            $userData = get_user_by_token($token);
            $data['user_id'] = $userData['user_id'];
        }

        // 2. 调用getWhere方法
        $where = static::$commonAnnouncementLogic->getWhere($data);

        // 3. 调用common层业务逻辑
        $list = static::$commonAnnouncementLogic->getAnnouncementList($where, 'id,title,content,image_url,type,announcement_status,sort,publish_time,create_time', 'sort DESC, publish_time DESC, id DESC', $data['limit'] ?? 20);

        // 4. 处理返回结果，添加用户已读状态和内容预览
        if (!empty($list)) {
            $userId = $data['user_id'] ?? 0;
            
            // 获取用户已读的公告ID列表
            $readIds = [];
            if ($userId > 0) {
                $announcementIds = array_column($list, 'id');
                $readIds = static::$commonAnnouncementLogic->modelAnnouncementRead->getUserReadAnnouncementIds($userId, $announcementIds);
            }
            
            foreach ($list as $key => $item) {
                $item['type_text'] = static::$commonAnnouncementLogic->modelAnnouncement->getTypeOptions()[$item['type']] ?? '未知';
                $item['status_text'] = static::$commonAnnouncementLogic->modelAnnouncement->getStatusOptions()[$item['announcement_status']] ?? '未知';
                $item['is_read'] = in_array($item['id'], $readIds);
                
                // 截取内容预览（去除HTML标签）
                $item['content_preview'] = mb_substr(strip_tags($item['content']), 0, 100) . '...';
                
                // 重新赋值修改后的数据
                $list[$key] = $item;
            }
        }

        return $list;
    }
    
    /**
     * 获取公告详情
     */
    public function getAnnouncementInfo($data = [])
    {
        // JWT解析获取user_id
        $token = $data['user_token'] ?? '';
        if (!empty($token)) {
            $userData = get_user_by_token($token);
            $data['user_id'] = $userData['user_id'] ?? 0;
        }
        
        // 调用common层业务逻辑
        $result = static::$commonAnnouncementLogic->getAnnouncementInfo($data);
        
        // 处理common层返回的[状态码, 消息, 数据]格式
        if (is_array($result) && isset($result[0])) {
            if ($result[0] == RESULT_SUCCESS) {
                return isset($result[2]) ? $result[2] : [];
            } else {
                return $this->returnError($result[1] ?? '获取失败');
            }
        }
        
        return $result;
    }
    
    /**
     * 获取最新公告
     */
    public function getLatestAnnouncement($data = [])
    {
        // JWT解析获取user_id
        $token = $data['user_token'] ?? '';
        if (!empty($token)) {
            $userData = get_user_by_token($token);
            $data['user_id'] = $userData['user_id'] ?? 0;
        }
        
        // 调用common层业务逻辑
        $result = static::$commonAnnouncementLogic->getLatestAnnouncement($data);
        
        // 处理common层返回的[状态码, 消息, 数据]格式
        if (is_array($result) && isset($result[0])) {
            if ($result[0] == RESULT_SUCCESS) {
                return isset($result[2]) ? $result[2] : [];
            } else {
                return $this->returnError($result[1] ?? '获取失败');
            }
        }
        
        return $result;
    }
    
    /**
     * 标记公告为已读
     */
    public function markAnnouncementAsRead($data = [])
    {
        // JWT解析获取user_id
        $token = $data['user_token'] ?? '';
        if (!empty($token)) {
            $userData = get_user_by_token($token);
            $data['user_id'] = $userData['user_id'] ?? 0;
        }
        
        // 调用common层业务逻辑
        $result = static::$commonAnnouncementLogic->markAnnouncementAsRead($data);
        
        // 处理common层返回的[状态码, 消息, 数据]格式
        if (is_array($result) && isset($result[0])) {
            if ($result[0] == RESULT_SUCCESS) {
                return isset($result[2]) ? $result[2] : '操作成功';
            } else {
                return $this->returnError($result[1] ?? '操作失败');
            }
        }
        
        return $result;
    }
    
    /**
     * 批量标记公告为已读
     */
    public function markMultipleAnnouncementsAsRead($data = [])
    {
        // JWT解析获取user_id
        $token = $data['user_token'] ?? '';
        if (!empty($token)) {
            $userData = get_user_by_token($token);
            $data['user_id'] = $userData['user_id'] ?? 0;
        }
        
        // 调用common层业务逻辑
        $result = static::$commonAnnouncementLogic->markMultipleAnnouncementsAsRead($data);
        
        // 处理common层返回的[状态码, 消息, 数据]格式
        if (is_array($result) && isset($result[0])) {
            if ($result[0] == RESULT_SUCCESS) {
                return isset($result[2]) ? $result[2] : '操作成功';
            } else {
                return $this->returnError($result[1] ?? '操作失败');
            }
        }
        
        return $result;
    }
    
    /**
     * 获取用户未读公告数量
     */
    public function getUnreadAnnouncementCount($data = [])
    {
        // JWT解析获取user_id
        $token = $data['user_token'] ?? '';
        if (!empty($token)) {
            $userData = get_user_by_token($token);
            $data['user_id'] = $userData['user_id'] ?? 0;
        }
        
        // 调用common层业务逻辑
        $result = static::$commonAnnouncementLogic->getUnreadAnnouncementCount($data);
        
        // 处理common层返回的[状态码, 消息, 数据]格式
        if (is_array($result) && isset($result[0])) {
            if ($result[0] == RESULT_SUCCESS) {
                return isset($result[2]) ? $result[2] : 0;
            } else {
                return $this->returnError($result[1] ?? '获取失败');
            }
        }
        
        return $result;
    }
    
    /**
     * 获取置顶公告
     */
    public function getTopAnnouncements($data = [])
    {
        // JWT解析获取user_id
        $token = $data['user_token'] ?? '';
        if (!empty($token)) {
            $userData = get_user_by_token($token);
            $data['user_id'] = $userData['user_id'] ?? 0;
        }
        
        // 调用common层业务逻辑
        $result = static::$commonAnnouncementLogic->getTopAnnouncements($data);
        
        // 处理common层返回的[状态码, 消息, 数据]格式
        if (is_array($result) && isset($result[0])) {
            if ($result[0] == RESULT_SUCCESS) {
                return isset($result[2]) ? $result[2] : [];
            } else {
                return $this->returnError($result[1] ?? '获取失败');
            }
        }
        
        return $result;
    }
}